import { createStoreBindings } from 'mobx-miniprogram-bindings'
import { store } from '@/utils/store'
import { call } from '@/utils/request'
import { showMsg, showLoading, hideLoading, showSuccess, showBookError } from '@/utils/toast'

let activity_id

Page({
  data: {
    activity: null,
  },
  async onLoad(options) {
    activity_id = options.id
    this.storeBindings = createStoreBindings(this, {
      store,
      fields: ['config', 'window_info'],
    })

    this.getOneActivity()
  },
  onShow() {},
  onUnload() {
    // 解绑
    this.storeBindings.destroyStoreBindings()
  },
  async getOneActivity() {
    showLoading()

    const res = await call('/getOneActivityById/' + activity_id)
    let date = new Date(res.book_date)
    const days = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
    res.day = days[date.getDay()]



    date = date.setDate(date.getDate() - 1)
    date = new Date(date)
    const m = date.getMonth() + 1
    const d = date.getDate()
    res.can_cancel_time =
      date.getFullYear() + '-' + (m < 10 ? '0' + m : m) + '-' + (d < 10 ? '0' + d : d)

    // for (let i = 0; i < res.user_total; i++) {
    //   const item = res.user_list[i]
    //   if (item) {
    //     if (item.nick_name && item.nick_name.length > 3) {
    //       item.nick_name = item.nick_name.slice(0, 1) + "*" + item.nick_name.slice(-2)
    //     }
    //   } else {
    //     res.user_list.push({
    //       avatar: '/images/default_avatar.svg'
    //     })
    //   }
    // }

    this.setData({
      activity: res,
    })

    setTimeout(() => {
      hideLoading()
    }, 500)
  },
  async onPullDownRefresh() {
    await this.getOneActivity()
    await wx.stopPullDownRefresh()
  },
  toUserListPage(date) {
    // call('/getVenueBookStatusOneDay/' + date).then(res => {
    //   my_booked_num = res.my_booked_num
    //   this.setData({
    //     bookSelectedList: [],
    //     oneDateBookMap: res.venue_book_status_one_day,
    //   })
    // })
  },
  onShareAppMessage() {
    var str = ''
    const {book_date, day, book_start_time: t1, book_end_time: t2} = this.data.activity
    var a1 = book_date.split('-')
    str += Number.parseInt(a1[1]) + '月' + Number.parseInt(a1[2]) + '日' + day + ' '


    if (t1 < 12) {
      str += "上午"
    } else if (t1 < 14) {
      str += "中午"
    } else if (t1 < 18) {
      str += "下午"
    } else {
      str += "晚上"
    }

    if (t1 > 12) {
      t1 -= 12
      t2 -= 12
    }

    str += t1 + ":00-" + t2 + ":00"

    str += '  训练'


    return {
      title: str,
      // path: '/pages/current/page',  // 默认当前页面路径（可省略）
      // imageUrl: '/images/share.jpg'  // 自定义缩略图（可选）
    }
  },
  showBigImage() {
    const { coach_img_path } = this.data.activity
    wx.previewImage({
      current: coach_img_path,
      urls: [coach_img_path],
    })
  },
  async toPay() {
    if (!store.user_info.mobile) {
      return wx.navigateTo({
        url: '/pages/auth_mobile/index',
      })
    }
    if (!store.user_info.avatar || !store.user_info.nick_name) {
      return wx.showModal({
        content: '报名活动前必须先完善个人信息！是否前往编辑页面？',
        confirmText: '前往',
        success (res) {
          if (res.confirm) {
            wx.navigateTo({
              url: '/pages/edit_user_info/index',
            })
          }
        }
      })
    }
    showLoading()
    const { id, out_trade_no, wx_pay_res } = await call('/payBookActivity/' + activity_id)
    hideLoading()
    wx_pay_res.package = wx_pay_res.packageVal
    wx.requestPayment(wx_pay_res)
      .then(() => {
        wx.showLoading({
          title: '正在支付...',
          mask: true,
        })
        this.paySuccess(id, out_trade_no)
      })
      .catch(res => {
        wx.redirectTo({
          url: '/pages/order_book_list/index',
        })
      })
  },
  paySuccess(id, out_trade_no) {
    const { PAID, ACTIVITY_SUCCESS } = this.data.config
    var timer = setInterval(async () => {
      call('/getOneOrderBookById/' + id).then(res => {
        if (res.status === PAID || res.status === ACTIVITY_SUCCESS) {
          const duration = showSuccess('支付成功！')
          clearInterval(timer)
          timer = undefined
          setTimeout(() => {
            wx.redirectTo({
              url: '/pages/order_book_list/index',
            })
          }, duration)
        }
      })
    }, 1000)

    setTimeout(() => {
      if (timer !== undefined) {
        call('/queryWxPayStatus/' + out_trade_no).catch(res => {
          clearInterval(timer)
          showBookError()
        })
      }
    }, 5000)
  },
})
